package com.whc.myblog.web;


import com.whc.myblog.NotFoundException;
import com.whc.myblog.service.interfaces.BlogService;
import com.whc.myblog.service.interfaces.TagService;
import com.whc.myblog.service.interfaces.TypeService;
import com.whc.myblog.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.crossstore.ChangeSetPersister;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.query.Param;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class indexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @GetMapping({"/","/index","/index.html"})
    public String index(@PageableDefault(size = 10,sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                        BlogQuery blog, Model model){
        //博客列表
        model.addAttribute("page", blogService.listBlog(pageable));
        //分类
        model.addAttribute("types",typeService.listTypeTop(6));
        //标签
        model.addAttribute("tags",tagService.listTagTop(10));
        //最新博客
        model.addAttribute("recommendBlogs",blogService.listRecommendBlogTop(8));
        return "index";
    }

    //搜索结果
    @PostMapping("/search")
    public String search(@PageableDefault(size = 10,sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         @RequestParam String query, Model model){
        model.addAttribute("page",blogService.listBlog("%"+query+"%",pageable));
        model.addAttribute("query",query);
        return "search";
    }


    @GetMapping("/type")
    public String type(){
        return "type";
    }
    @GetMapping("/tag")
    public String tag(){
        return "tag";
    }
//    @GetMapping("/archive")
//    public String archive(){
//        return "archive";
//    }


    //博客详情
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model){
        model.addAttribute("blog", blogService.getAndConvert(id));
        return "blog";
    }
}
